<template>
  <div class="containers h-100vh w-100vw flex bg-#f6f6f6">
    <!-- 头部检索 -->
    <div class="bg bg-#039595">
      <div class="header w-100%" :style="{
        minHeight: queryParms.searchType ? '' : '150px'
      }">
        <div class="logo">
          <img src="@/assets/imgs/logo.png" alt="" class="m-l-20px m-r-5px h-25px w-30px" />
          <span>新闻传播中心出版社</span>
        </div>
        <div class="retrievalPart w-50% flex" :style="{
          minHeight: queryParms.searchType ? '200px' : '150px'
        }">
          <div class="searchMethod h-50px w-100% cursor-pointer text-#fff">
            <h2 class="h-100% text-center">
              {{ !queryParms.searchType ? '检索' : '高级检索'
              }}<span class="m-l-10px text-15px" @click="() => (
                queryParms.searchType
                  ? (queryParms.searchType = 0)
                  : (queryParms.searchType = 1),
                getdata()
              )
                ">{{ queryParms.searchType ? '返回' : '高级检索' }}>></span>
            </h2>
          </div>
          <div class="retrieval w-100% flex justify-around">
            <!-- 标准检索 -->
            <el-autocomplete v-if="!queryParms.searchType" v-model="queryParms.keyWord" placeholder="请输入检索内容"
              class="input-with-select input-with-suffix-icon" :suffix-icon="Camera" :fetch-suggestions="querySearch"
              :trigger-on-focus="false" clearable @select="handleSelect" size="20px">
              <template #prepend>
                <!-- <select v-model="retrievalType" placeholder="Select" class="searchSelect h-45px border-none"
                  style="width: 85px; padding-left: 8px"> -->
                <!-- <span v-for="item in retrievalOptions" :key="item.value" :label="item.label" :value="item.value">
                  {{ item.label }}
                </span> -->
                <!-- </select> -->
                <select disabled v-model="retrievalType" placeholder="Select" class="searchSelect h-45px border-none"
                  style="width: 85px; padding-left: 8px; appearance: none;">
                  <option v-for="item in retrievalOptions" :key="item.value" :label="item.label" :value="item.value">
                  </option>
                </select>
              </template>
              <template #append>
                <el-button :icon="Search" class="searchbtn" @click="() => (getdata(), (isSearch = true))" />
              </template>
            </el-autocomplete>
            <!-- 普通检索 -->
            <el-form v-else :model="queryParms" class="form m-t-10px box-border w-100%">
              <el-form-item class="form_item box-border p-10px">
                <el-row :gutter="10">
                  <el-col :span="5">
                    <el-select v-model="selectType" placeholder="请选择检索类型" :disabled="true">
                      <el-option style="padding: 0 32px 0 20px" label="出版时间" :value="selectType" />
                    </el-select>
                  </el-col>
                  <!-- 普通检索 -->
                  <el-col :span="15">
                    <el-date-picker v-model="publicationTime" type="daterange" range-separator="To"
                      start-placeholder="请输入起始时间" end-placeholder="请输入终止时间" style="width: 96.5%" />
                  </el-col>
                  <el-col :span="3">
                    <div class="box-border flex"></div>
                  </el-col>
                </el-row>
              </el-form-item>
              <el-form-item class="form_item box-border p-10px" v-for="(its, inds) in queryParms.advancedSearches"
                :key="inds">
                <el-row :gutter="10" v-if="inds == 0">
                  <el-col :span="5">
                    <el-select v-model="its.fnType" placeholder="请选择检索类型" clearable>
                      <el-option style="padding: 0 32px 0 20px" :label="ites.label" :value="ites.value"
                        v-for="ites in typeOptions" :key="ites.value" />
                    </el-select>
                  </el-col>
                  <!-- 普通检索 -->
                  <el-col :span="15">
                    <el-input v-model="its.keyWord" placeholder="请输入检索内容" clearable @input="isSearch = false"
                      :suffix-icon="its.fnType === 'fnPics' ? Camera : ''" />
                  </el-col>
                  同音查询：
                  <el-switch v-model="queryParms.homo"></el-switch>
                  <el-popover placement="top-start" effect="dark" :width="180" trigger="hover"
                    content="同音词查询功能只支持“标题”或“名称”查询">
                    <template #reference>
                      <el-icon>
                        <QuestionFilled />
                      </el-icon>
                    </template>
                  </el-popover>
                  <el-col :span="3">
                    <div class="box-border flex">
                      <el-button type="primary" v-if="
                        inds + 1 == queryParms.advancedSearches.length &&
                        queryParms.advancedSearches.length <= 4
                      " class="addbtn" @click="addCondition">+</el-button>
                      <el-button type="primary" v-if="inds != 0" class="addbtn"
                        @click="delCondition(index)">-</el-button>
                    </div>
                  </el-col>
                </el-row>
                <el-row :gutter="10" v-else>
                  <el-col :span="5">
                    <el-select v-model="its.symbol" placeholder="请选择检索条件" clearable>
                      <el-option style="padding: 0 32px 0 20px" :label="ites.label" :value="ites.value"
                        v-for="ites in conditionOptions2" :key="ites.value" />
                    </el-select>
                  </el-col>
                  <el-col :span="5">
                    <el-select v-model="its.fnType" placeholder="请选择检索类型" clearable>
                      <el-option style="padding: 0 32px 0 20px" :label="ites.label" :value="ites.value"
                        v-for="ites in typeOptions" :key="ites.value" />
                    </el-select>
                  </el-col>
                  <!-- 标准检索 -->
                  <el-col :span="10">
                    <el-input v-model="its.keyWord" placeholder="请输入检索内容" clearable @input="isSearch = false" />
                  </el-col>
                  <el-col :span="3">
                    <div class="box-border flex">
                      <el-button type="primary" v-if="
                        inds + 1 == queryParms.advancedSearches.length &&
                        queryParms.advancedSearches.length <= 4
                      " class="addbtn" @click="addCondition">+</el-button>
                      <el-button type="primary" v-if="inds != 0" class="addbtn"
                        @click="delCondition(index)">-</el-button>
                    </div>
                  </el-col>
                </el-row>
              </el-form-item>
            </el-form>
            <div class="searchBtn h-50px flex items-center justify-center" v-show="queryParms.searchType">
              <el-button type="primary" @click="() => ((isSearch = true), getdata())" class="p-10px">检索</el-button>
              <el-button @click="reset">重置</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 库类型 -->
    <div class="typeList box-border h-50px w-100% bg-#207073">
      <ul class="m-0px h-100% flex items-center justify-evenly">
        <li class="box-border h-100% w-80px flex cursor-pointer items-center justify-center text-14px text-#fff"
          v-for="(item, index) in libraryType" :key="index" @click="activeTab(item.value)"
          :style="{ backgroundColor: queryParms.listSet == item.value ? '#039595' : '' }">
          <p>{{ item.label }}</p>
          <span>{{ item.size }}</span>
        </li>
      </ul>
    </div>
    <!-- 排序 -->
    <div class="sort box-border flex items-center justify-between bg-#fff p-l-25px p-r-25px text-15px">
      <div class="retrievalValue w-15%">
        全文检索：{{
          isSearch
            ? queryParms.searchType == 0
              ? queryParms.keyWord
              : queryParms.advancedSearches.map((it) => it.keyWord).join('、')
            : ''
        }}
      </div>
      <div class="sortList flex flex-1 items-center">
        排序：
        <div :class="['timeSort', 'item', activeSort == 'time' ? 'activeSort' : '']" @click="toggleSort('time')">
          发布时间
          <el-icon v-if="sortDirection === 'asc'">
            <CaretTop />
          </el-icon>
          <el-icon v-else>
            <CaretBottom />
          </el-icon>
        </div>
        <div :class="['item', activeSort == 'price' ? 'activeSort' : '']" @click="toggleSort('price')">
          价格
          <el-icon v-if="sortPrice === 'asc'">
            <CaretTop />
          </el-icon>
          <el-icon v-else>
            <CaretBottom />
          </el-icon>
        </div>
        <div :class="['item', activeSort == 'relevance' ? 'activeSort' : '']" @click="toggleSort('relevance')">
          相关度
          <el-icon v-if="sortRelevance === 'asc'">
            <CaretTop />
          </el-icon>
          <el-icon v-else>
            <CaretBottom />
          </el-icon>
        </div>
        <div :class="['item', activeSort == 'downloads' ? 'activeSort' : '']" @click="toggleSort('downloads')">
          下载量
          <el-icon v-if="sortDownloads === 'asc'">
            <CaretTop />
          </el-icon>
          <el-icon v-else>
            <CaretBottom />
          </el-icon>
        </div>
      </div>
    </div>
    <!-- 内容和分类 -->
    <div class="contents w-100% flex">
      <!-- 树形分类 -->
      <div class="classification" v-loading="treeLoading" element-loading-text="加载中...">
        <el-tree ref="treeRef" :default-expanded-keys="[278]" node-key="id" :data="classificationList" :props="{
          label: 'name',
          children: 'childMenu'
        }" show-checkbox @check="handleCheckChange" :render-content="renderContent" />
      </div>
      <!-- 检索结果列表 -->
      <div class="results h-100% flex items-center justify-between" v-loading="loadings" element-loading-text="加载中...">
        <div class="searchResults w-100%" v-if="dataList.length !== 0">
          <div class="results_item box-border h-180px flex items-center bg-#fff p-15px"
            v-for="(item, index) in dataList" style="cursor: pointer" :key="index">
            <!-- 这里的路径和参数根据你的实际情况设置 -->
            <div class="index text-center text-16px">
              {{ index + 1 < 10 ? '0' + (index + 1) : index + 1 }} </div>
                <div v-if="[1, 6].includes(queryParms.listSet)">
                  <img @click="openNewBookWindow(queryParms.listSet, item.fnId)"
                    class="border-2px border-#e0e3e9 border-solid" height="160"
                    :src="item.url || '@/assets/images/error.png'" alt="" />
                </div>
                <div v-else-if="[4].includes(queryParms.listSet)" class="search-content">
                  <el-image style="width: 100px; height: 100px" :src="item.fnUrl || '@/assets/images/error.png'"
                    :zoom-rate="1.2" :max-scale="7" :min-scale="0.2" :preview-src-list="[item.fnUrl]" :initial-index="4"
                    fit="cover" />
                </div>
                <div v-else-if="[2].includes(queryParms.listSet)" class="search-content">
                  <video controls :id="'my-video' + index" class="video-js vjs-default-skin" preload="auto"
                    @timeupdate="timeupdate" width="250px" height="160px">
                    <source :src="item.fnUrl" />
                  </video>
                </div>
                <div class="results_content m-l-10px h-100% w-85% flex text-13px">
                  <div class="title" @click="openNewBookWindow(queryParms.listSet, item.fnId)"
                    v-html="highlightedContent(item.fnTitle ? item.fnTitle : '暂无标题')"></div>
                  <div class="code">
                    <span class="m-l-1px">【{{ libraryType.find((it) => it.value === queryParms.listSet).label
                      }}】</span>DOI：{{ item.fnCover ? JSON.parse(item.fnCover)[0]?.doi || '' : '-' }}
                  </div>
                  <el-tooltip effect="light" placement="top">
                    <template #content>
                      <div class="popper" v-html="highlightedContent(item.fnBrief ? item.fnBrief.replace(/<[^>]*>/g, '') : '')
                        "></div>
                    </template>
                    <div class="abstract cursor-pointer">
                      <b>摘要：</b>
                      <span v-html="highlightedContent(
                        item[fieldMapping[queryParms.listSet].abstract]
                          ? item[fieldMapping[queryParms.listSet].abstract].replace(/<[^>]*>/g, '')
                          : ''
                      )
                        "></span>
                    </div>
                  </el-tooltip>
                  <div :class="[item.author ? 'author' : '']">
                    <p>
                      <b>作者：</b><span v-html="highlightedContent(item.fnAuthor ? item.fnAuthor.replace(/<[^>]*>/g, '') : '')
                        "></span>
                    </p>
                  </div>
                  <div class="press">
                    <p><b>出版社：</b>{{ item.fnPublishername || item.fnPublish }}</p>
                  </div>
                  <div class="keywords">
                    <p>
                      <b>关键字：</b><span v-for="(it, ind) in item.fnKeyword ? item.fnKeyword.split('，') : []" :key="ind"
                        @click="performSearch(it ? it : '')" v-html="highlightedContent(it ? it : '', '关键字')"></span>
                    </p>
                  </div>
                </div>
                <div v-if="[1].includes(queryParms.listSet)" class="book-right-button">
                  <el-button @click="handleJump(item)" plain type="success" :icon="List">相关图谱</el-button>
                </div>
            </div>
          </div>
          <div v-else>
            <el-empty description="暂无数据..." />
          </div>
          <div class="paging">
            <el-pagination background :page-size="queryParms.size" layout="prev, pager, next" :total="total"
              v-model:current-page="queryParms.page" next-text="下一页 >" prev-text="< 上一页"
              @current-change="handleCurrentChange" />
          </div>
        </div>
      </div>
    </div>
</template>
<script lang="tsx" setup>
import videojs from 'video.js'
import 'video.js/dist/video-js.css'
import { onMounted, reactive, toRefs } from 'vue'
import ICON from '@/assets/imgs/ICON.png'
import { Camera, Search, List } from '@element-plus/icons-vue'
import * as SearchApi from '@/api/search'
import FormatDate from '@/utils/dateFormat'
import bookLogo from '@/assets/imgs/bookLogo.webp'
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()
interface RestaurantItem {
  value: string
  link: string
}
// 自动补全数据源
const querySearch = (queryString, cb) => {
  if (queryString.length > 0) {
    queryParms.value.keyWord = queryString
    SearchApi.getAssociationalWords(queryParms.value).then((res) => {
      cb(res.map((item: any) => {
        return {
          value: item.value,
          link: item.link
        }
      }))
    })
  } else {
    cb([])
  }
}
const handleSelect = (item: RestaurantItem) => {
  console.log(item)
}
// 相关图谱
const handleJump = (rowData) => {
  console.log(rowData)
  // router.push({
  //   path: '/knowledge/nodeMaintenance/visualization',
  //   query: {
  //     // graphName: route.query.graphName,
  //     // graphId: route.query.graphId,
  //     // entity: data.rowData.entityName
  //   }
  // })
  // const url = `${window.location.origin}/retrieval/book/detail?metaId=${metaId}&detailsId=${id}&buttonState=${false}`
  const url = `${window.location.origin}/knowledge/nodeMaintenance/visualization`
  window.open(url, '_blank')
}
// 定义 videojs 实例
const myPlayer = ref()
// videojs 初始化函数
function initVideoSource() {
  console.log(dataList.value)
  dataList.value.map((item, index) => {
    myPlayer.value = videojs('my-video' + index, {
      width: '250px', //播放器高度
      height: '160px', //播放器高度
      controls: true, // 是否显示控制条
      preload: 'auto',
      autoplay: false, // 自动播放
      loop: false, // 循环播放
      // fluid: true, // 自适应宽高
      language: 'zh-CN', // 设置语言
      muted: true, // 是否静音
      inactivityTimeout: false,
      // 设置控制条组件
      controlBar: {
        // 设置控制条组件
        //  设置控制条里面组件的相关属性及显示与否
        currentTimeDisplay: true,
        timeDivider: true,
        durationDisplay: true,
        remainingTimeDisplay: false,
        volumePanel: {
          inline: false
        },
        pictureInPictureToggle: false
      },
      userActions: {
        seek: false
      }
    })
  })
}
const timeupdate = (e) => {
  console.log(e)
  console.log(e.target.currentTime)
}
const selectType = ref('')
const publicationTime = ref('')
// tabs栏下渲染字段映射关系
const listSetArray = [1, 2, 3, 4, 5]
const fieldMapping = reactive({
  // 0: {
  //   listSet: 0,
  //   abstract: 'fnBrief',
  //   author: 'fnAuthor',
  //   press: 'fnPublishername',
  //   keywords: 'fnKeyword'
  // }, // 初始加载
  1: {
    listSet: 1,
    abstract: 'fnBrief',
    author: 'fnAuthor',
    press: 'fnPublishername',
    keywords: 'fnKeyword'
  }, // 图书
  2: {
    listSet: 2,
    abstract: 'fnBrief',
    author: 'fnAuthor',
    press: 'fnPublishername',
    keywords: 'fnKeyword'
  }, // 视频
  3: {
    listSet: 3,
    abstract: 'fnBrief',
    author: 'fnAuthor',
    press: 'fnPublishername',
    keywords: 'fnKeyword'
  }, // 音频
  4: {
    listSet: 4,
    abstract: 'fnBrief',
    author: 'fnAuthor',
    press: 'fnPublishername',
    keywords: 'fnKeyword'
  }, // 图片
  5: {
    listSet: 5,
    abstract: 'fnBrief',
    author: 'fnAuthor',
    press: 'fnPublishername',
    keywords: 'fnKeyword'
  } // 期刊
  // 6: {
  //   listSet: 6,
  //   abstract: 'fnBrief',
  //   author: 'fnAuthor',
  //   press: 'fnPublishername',
  //   keywords: 'fnKeyword'
  // }, // 问答
  // 7: {
  //   listSet: 7,
  //   abstract: 'fnBrief',
  //   author: 'fnAuthor',
  //   press: 'fnPublishername',
  //   keywords: 'fnKeyword'
  // }, // 案例
  // 7: {
  //   listSet: 8,
  //   abstract: 'fnBrief',
  //   author: 'fnAuthor',
  //   press: 'fnPublishername',
  //   keywords: 'fnKeyword'
  // }, // 释义
  // 7: {
  //   listSet: 9,
  //   abstract: 'fnBrief',
  //   author: 'fnAuthor',
  //   press: 'fnPublishername',
  //   keywords: 'fnKeyword'
  // }, // 网络信息
  // 7: {
  //   listSet: 10,
  //   abstract: 'fnBrief',
  //   author: 'fnAuthor',
  //   press: 'fnPublishername',
  //   keywords: 'fnKeyword'
  // } // 资料档案
})
// 数据定义
const data = reactive({
  isSearch: false, //是否是搜索
  retrievalType: 0, //标准检索条件
  retrievalOptions: [
    { value: 0, label: '全文检索' }
    // { value: 1, label: '二次检索' }
  ], //标准检索下拉
  total: 0, //检索列表内容总数
  treeLoading: false, //树形分类loading
  queryParms: {
    keyWord: '', //标准检索关键字
    keyWord1: '', //标准二次检索关键字
    searchType: 0, //检索条件类型 0标准 1高级
    ts: '', //发布时间排序 1正序 否则为倒序
    homo: false, //同音词是否开启
    pr: '', //价格排序 1正序 否则为倒序
    re: '', //相关度 1正序 否则为倒序
    downloads: '', //下载量排序 1正序 否则为倒序
    sort: [], //282 //分类类型
    advancedSearches: [
      {
        fnType: 'fnTitle', //普通检索类型
        keyWord: '', //普通检索关键字
        option: '1', //普通检索内容是否包含
        symbol: '==', // 普通检索条件 与为== 或为||
        startScope: 1, // 出版时间状态
        startTime: '', // 出版起始时间
        endTime: '' // 出版终止时间
      }
    ], //普通检索参数
    page: 1,
    size: 10,
    listSet: 1
  }, //列表请求参数
  sortDirection: 'desc', // 发布时间排序方向为升序：desc 倒序：asc
  sortPrice: 'asc', //价格排序方向为升序：asc，倒序desc
  sortRelevance: 'asc', //相关度排序方向为升序：asc，倒序desc
  sortDownloads: 'asc', //下载量 排序方向为升序：asc，倒序desc
  activeSort: 'time', // 排序选项为发布时间：time  下载量:downloads 相关度：relevance 价格：price
  classificationList: [], //树形分类
  loadings: false, //检索列表loading
  dataList: [], //检索列表
  conditionOptions: [
    { label: '包含', value: 1 },
    { label: '不包含', value: 2 }
  ], //普通检索条件
  conditionOptions2: [
    { label: '与', value: '==' },
    { label: '或', value: '||' }
  ], //普通检索条件
  typeOptions: [
    {
      label: '标题',
      value: 'fnTitle'
    },
    {
      label: '图书简介',
      value: 'fnBrief'
    },
    {
      label: '关键词',
      value: 'fnKeyword'
    },
    {
      label: '封面',
      value: 'fnCover'
    },
    {
      label: '人脸识别',
      value: 'fnPics'
    }
  ] //检索类型
})
// 数据响应式
let {
  retrievalType,
  retrievalOptions,
  retrievalValue,
  sortDirection,
  sortPrice,
  sortRelevance,
  sortDownloads,
  activeSort,
  classificationList,
  dataList,
  conditionOptions,
  conditionOptions2,
  typeOptions,
  queryParms,
  loadings,
  total,
  treeLoading,
  isSearch,
  valueSetList
} = toRefs(data)
// 初始化-获取检索分类和检索列表
onMounted(() => {
  activeTab(1)
  addCondition()
  getClassification()
})
watch(
  () => queryParms.value.listSet,
  // 移出视频栏目时，销毁videojs
  (newValue, oldValue) => {
    if (oldValue === 2)
      if (myPlayer.value) {
        dataList.value.map((item, index) => {
          console.log(item)
          console.log(index)
          var player = videojs('my-video' + index)
          player.dispose() // 销毁播放器实例
        })
      }
  }
  // { immediate: true, deep: true }
)
const openNewBookWindow = (type, id) => {
  console.log(type, id)
  console.log(window.location.origin)
  if (type === 1) {
    // 图书详情
    const metaId = 42
    // const url = `${window.location.origin}/retrieval/books?metaId=${metaId}&detailsId=${id}`
    const url = `${window.location.origin}/retrieval/book/detail?metaId=${metaId}&detailsId=${id}&buttonState=${false}`
    window.open(url, '_blank')
  } else if (type === 2) {
    // 视频详情
    const url = `${window.location.origin}/retrieval/video/detail?id=${id}&buttonState=${false}`
    // const url = `${window.location.origin}/retrieval/video/detail?id=${id}&buttonState=${false}`
    window.open(url, '_blank')
  } else if (type === 3) {
    // 音频详情
  } else if (type === 4) {
    // 图片详情
  } else if (type === 5) {
    // 期刊详情
  } else if (type === 6) {
    // 问答详情
  } else if (type === 7) {
    // 案例详情
  } else if (type === 8) {
    // 释义详情
  } else if (type === 9) {
    // 网络信息详情
  } else if (type === 10) {
    // 资料档案详情
  } else {
  }
}
// 切换排序方式
const toggleSort = (sortType) => {
  if (sortType === activeSort.value) {
    if (sortType === 'time') {
      sortDirection.value = sortDirection.value === 'asc' ? 'desc' : 'asc' // 切换排序方向
      queryParms.value.ts = sortDirection.value === 'asc' ? '1' : '0'
      queryParms.value.pr = ''
      queryParms.value.re = ''
      queryParms.value.downloads = ''
    } else if (sortType === 'price') {
      sortPrice.value = sortPrice.value === 'asc' ? 'desc' : 'asc'
      queryParms.value.pr = sortPrice.value === 'asc' ? '1' : '0'
      queryParms.value.ts = ''
      queryParms.value.re = ''
      queryParms.value.downloads = ''
    } else if (sortType === 'relevance') {
      sortRelevance.value = sortRelevance.value === 'asc' ? 'desc' : 'asc'
      queryParms.value.re = sortRelevance.value === 'asc' ? '1' : '0'
      queryParms.value.ts = ''
      queryParms.value.pr = ''
      queryParms.value.downloads = ''
    } else if (sortType === 'downloads') {
      sortDownloads.value = sortDownloads.value === 'asc' ? 'desc' : 'asc'
      queryParms.value.downloads = sortDownloads.value === 'asc' ? '1' : '0'
      queryParms.value.ts = ''
      queryParms.value.re = ''
      queryParms.value.pr = ''
    }
    getdata()
  } else {
    activeSort.value = sortType // 更新高亮的排序选项
    // sortDirection.value = 'asc' // 重置排序方向为升序
  }
  // 执行相应的排序操作
  if (sortDirection.value === 'asc') {
  } else {
  }
}
// 切换分页
const handleCurrentChange = (val) => {
  console.log(val)
  queryParms.value.page = val
  getdata()
}
// 普通检索添加检索条件
const addCondition = () => {
  console.log('普通检索添加检索条件')
  queryParms.value.advancedSearches.push({
    fnType: 'fnTitle',
    keyWord: '',
    option: '1',
    symbol: '=='
  })
}
// 普通检索删除检索条件
const delCondition = (index) => {
  queryParms.value.advancedSearches.splice(index, 1)
}
// 普通检索重置
const reset = () => {
  queryParms.value.advancedSearches[0].fnpics = ''
  publicationTime.value = ''
  queryParms.value.advancedSearches = [
    {
      fnType: 'fnTitle', //普通检索类型
      keyWord: '', //普通检索关键字
      option: '1', //普通检索内容是否包含
      symbol: '==' // 普通检索条件 与为== 或为||
    }
  ]
  queryParms.value.page = 1
  isSearch.value = false
  getdata()
}
const performSearch = async (keyword) => {
  if (!queryParms.value.searchType) {
    queryParms.value.advancedSearches = []
  } else if (!isSearch.value) {
    queryParms.value.advancedSearches = [
      {
        fnType: 'fnTitle',
        keyWord: '',
        option: '1',
        symbol: '=='
      }
    ]
    queryParms.value.keyWord1 = ''
  }
  // 将关键字赋值给 queryParms.value.keyWord1
  queryParms.value.keyWord1 = keyword
  try {
    loadings.value = true
    const data = await SearchApi.getRetrievalList(queryParms.value)
    dataList.value = data.list.map((item) => {
      return {
        ...item,
        url: item.fnCover ? JSON.parse(item.fnCover)[0].url : '',
        fnKeyword: item.fnKeyword
      }
    })
    total.value = data.total
    loadings.value = false
  } catch (error) {
    dataList.value = []
    console.error(error)
    loadings.value = false
  }
}
// 获取检索列表
const getdata = async () => {
  activeTabFields(data.queryParms.listSet)
  console.log(queryParms.value)
  console.log(queryParms.value.searchType)
  console.log(publicationTime.value)
  if (!queryParms.value.searchType) {
    queryParms.value.advancedSearches = []
  } else if (!isSearch.value) {
    queryParms.value.advancedSearches = [
      {
        fnType: 'fnTitle',
        keyWord: '',
        option: '1',
        symbol: '=='
      },
      {
        fnType: 'fnTitle',
        keyWord: '',
        option: '1',
        symbol: '=='
      }
    ]
    queryParms.value.keyWord = ''
  }
  if (queryParms.value.searchType === 1) {
    if (!queryParms.value.advancedSearches[0].keyWord) {
      console.log('keyWord')
      queryParms.value.advancedSearches[0].keyWord = queryParms.value.advancedSearches[1].keyWord
      queryParms.value.advancedSearches[0].fnType = queryParms.value.advancedSearches[1].fnType
    }
  }
  if (publicationTime.value) {
    queryParms.value.advancedSearches.forEach((item, index) => {
      item.startScope = 1
      item.startTime = FormatDate.prototype.formatDate(
        new Date(publicationTime.value[0]),
        'yyyy-MM-dd'
      )
      item.endTime = FormatDate.prototype.formatDate(
        new Date(publicationTime.value[1]),
        'yyyy-MM-dd'
      )
    })
  } else {
    queryParms.value.advancedSearches.forEach((item, index) => {
      item.startScope = 0
      item.startTime = ''
      item.endTime = ''
    })
  }
  try {
    loadings.value = true
    if (queryParms.value.advancedSearches[1])
      queryParms.value.advancedSearches[0].symbol = queryParms.value.advancedSearches[1].symbol
    const data = await SearchApi.getRetrievalList(queryParms.value).then((res) => {
      return res
    })
    dataList.value = data.list.map((item) => {
      return {
        ...item,
        url:
          item.fnCover && item.fnCover !== '[]' ? JSON.parse(item.fnCover)[0]?.url || '' : bookLogo
      }
    })
    libraryType.value.find((item) => item.value === queryParms.value.listSet).size = data.total
    total.value = data.total
    loadings.value = false
    // 接口有数据并且tabs栏目选项为视频时执行
    if (dataList.value.length > 0) if (queryParms.value.listSet === 2) increment()
  } catch (error) {
    dataList.value = []
    console.error(error)
    loadings.value = false
  }
}
// DOM更新后执行videojs初始化函数
async function increment() {
  await nextTick()
  initVideoSource()
}
const libraryType = ref([
  {
    label: '图书',
    value: 1,
    size: 0,
    dataList: []
  },
  {
    label: '视频',
    value: 2,
    size: 0,
    dataList: []
  },
  {
    label: '音频',
    value: 3,
    size: 0,
    dataList: []
  },
  {
    label: '图片',
    value: 4,
    size: 0,
    dataList: []
  },
  {
    label: '期刊',
    value: 5,
    size: 0,
    dataList: []
  }
  // {
  //   label: '问答库',
  //   value: 6,
  //   size: 0
  // },
  // {
  //   label: '案例库',
  //   value: 7,
  //   size: 0
  // },
  // {
  //   label: '释义库',
  //   value: 8,
  //   size: 0
  // },
  // {
  //   label: '网络信息库',
  //   value: 9,
  //   size: 0
  // },
  // {
  //   label: '资料档案库',
  //   value: 10,
  //   size: 0
  // }
])
// 获取树形分类列表
const getClassification = async () => {
  try {
    treeLoading.value = true
    // const res = await SearchApi.getClassificationList()
    const res = await SearchApi.getClassificationList('book')
    classificationList.value = res.map((item) => {
      return {
        ...item,
        isAllExpand: false,
        isExpand: false
      }
    })
    classificationList.value.sort(function (a, b) {
      return a.childMenu.length - b.childMenu.length
    })
    treeLoading.value = false
  } catch (error) {
    treeLoading.value = false
    console.log(error)
  }
}

//切换库类型对应的检索条件
const bookFields = data.typeOptions
const videoFields = [
  {
    label: '视频名称',
    value: 'fnTitle'
  },
  {
    label: '来源',
    value: 'source'
  }
]
const audioFields = [
  {
    label: '音频名称',
    value: 'fnTitle'
  }
]
const pictureFields = [
  {
    label: '图片名称',
    value: 'fnTitle'
  }
]
const periodicalFields = [
  {
    label: '期刊名称',
    value: 'fnTitle'
  }
]
const activeTabFields = (value) => {
  console.log('获取的标识是' + value)
  switch (value) {
    case 1:
      data.typeOptions = bookFields
      break
    case 2:
      data.typeOptions = videoFields
      break
    case 3:
      data.typeOptions = audioFields
      break
    case 4:
      data.typeOptions = pictureFields
      break
    case 5:
      data.typeOptions = periodicalFields
      break
  }
}

// 切换库类型
const activeTab = (value) => {
  queryParms.value.listSet = value
  getdata()
}
// 切换库类型
const getRetrievalListData = []
const numberTypeListFcn = async (value) => {
  const params = {
    keyWord: '',
    keyWord1: '',
    searchType: 0,
    ts: 0,
    sort: [],
    advancedSearches: [],
    page: 1,
    size: 10,
    listSet: value
  }
  const data = await SearchApi.getRetrievalList(params)
  libraryType.value
    .filter((item) => item.value === value)
    .forEach((item) => {
      item.size = data.total
    })
}
// 调用函数并获取返回的对象
listSetArray.forEach((item) => numberTypeListFcn(item))
// 树形组件实例
const treeRef = ref()
// 自定义内容渲染树形列表
const renderContent = (h, { node, data, store }) => {
  const { valueSetList } = data
  return h(
    'span',
    {
      class: `w-100% text-#fff m-l-4px treeContent ${node.level == 1 ? 'p-l-50px' : 'p-0px'}`,
      title: node.label
    },
    h('img', {
      class: `${node.level == 1 ? 'w-15px m-r-5px' : 'w-0px'}  align-middle`,
      src: ICON
    }),
    h(
      'span',
      { class: `${node.level == 1 ? 'text-15px' : 'text-14px'}` },
      `${node.label}${data.setMap !== null ? '（' + data.setMap + '）' : ''} ${node.level !== 1 && data.value ? '(' + data.value + ')' : ''
      }`
    )
  )
}

// 树形组件复选框选中事件
const handleCheckChange = (data, checked, indeterminate) => {
  queryParms.value.sort = treeRef.value.getCheckedKeys()
  getdata()
}

// 高亮关键字
const highlightedContent = (content, type) => {
  if (content.replace) if (!isSearch.value) return content
  if (queryParms.value.searchType == 0) {
    isSearch.value = false
    return content
  } else {
    const searchTerms = queryParms.value.advancedSearches.map((it) => it.keyWord.toLowerCase())
    const regex = new RegExp(searchTerms.join('|'), 'gi')
    return content.replace(
      regex,
      (match) => `<span style="color:red; font-weight: 600;">${match}</span>`
    )
  }
}
const openSearchImage = () => {
  console.log('以图搜图')
}
</script>

<style lang="scss" scoped>
::v-deep(.vjs-big-play-button) {
  top: calc((160px - 1.63332em) / 2);
  left: calc((250px - 3em) / 2);
}

// ::v-deep(.demo-image__error .image-slot) {
//   font-size: 30px;
// }

// ::v-deep(.demo-image__error .image-slot .el-icon) {
//   font-size: 30px;
// }

// ::v-deep(.demo-image__error .el-image) {
//   width: 100%;
//   height: 200px;
// }

.input-with-suffix-icon {
  ::v-deep(.el-input__suffix) {
    font-size: 20px;
  }
}

@font-face {
  font-family: HarmonyOS;
  src: url('@/assets/font/HarmonyOS_Sans_SC_Regular.ttf');
}

p {
  padding: 0;
  margin: 0;
}

*,
body,
html {
  font-family: HarmonyOS;
  user-select: none;
  /* 火狐 */
  /* 选中文字时避免出现蓝色背景 */
  user-select: none;
  /* webkit浏览器 */
  /* 选中文字时避免出现蓝色背景 */
  user-select: none;
  /* IE10 */
  /* 选中文字时避免出现蓝色背景 */
  user-select: none;
  /* 选中文字时避免出现蓝色背景 */
}

.containers {
  flex-direction: column;
  font-family: 'Microsoft YaHei';

  .header {
    position: relative;
    min-height: 200px;
    background: url('../../assets//imgs/headerbg.png') no-repeat;
    background-size: 100% 100%;

    .logo {
      position: absolute;
      top: 20px;
      left: 50;

      img {
        vertical-align: middle;
      }

      span {
        margin-top: 2px;
        font-size: 14px;
        color: #fff;
      }
    }

    .retrievalPart {
      height: 100%;
      margin: auto;
      flex-direction: column;
      justify-content: space-evenly;

      .searchMethod {}

      .retrieval {
        height: 100%;
        flex-direction: column;
        justify-content: space-evenly;

        .form {
          display: flex;
          overflow: auto;
          flex-direction: column;

          &::-webkit-scrollbar {
            width: 8px; // y轴滚动条宽度
            height: 5px; // x轴滚动条宽度
            background-color: #207073;
            border-radius: 5px;
          }

          &::-webkit-scrollbar-thumb {
            background-image: -webkit-gradient(linear,
                left bottom,
                left top,
                color-stop(0.44, #039595));
            border-radius: 5px;
            box-shadow: inset 0 0 6px #f4f4f5;
          }

          .form_item {
            padding: 0;
            margin: 0;
          }
        }

        .searchSelect {
          line-height: 45px;
          border-radius: 25px 0 0 25px;
          outline: none;
          box-shadow: 0 0 0 0.5px var(--el-input-border-color, var(--el-border-color)) inset;

          option {
            height: 45px;
            line-height: 45px;
          }
        }

        .retrievalInput {
          border-radius: 0;
        }

        :deep(.el-input-group__append) {
          width: 30px;
          font-size: 28px;
          color: #fff;
          background-color: #039595;
          border-radius: 0 25px 25px 0;
        }
      }
    }
  }

  .typeList {
    padding-left: 10px;

    ul {
      li {
        flex-direction: column;
        margin: 0 10px;

        p {
          margin: 0;
        }

        span {
          font-size: 13px;
        }
      }
    }
  }

  .sort {
    max-height: 40px;
    min-height: 40px;

    .retrievalValue {}

    .sortList {
      .item {
        display: flex;
        width: 100px;
        font-size: 14px;
        cursor: pointer;
        align-items: center;
      }

      .activeSort {
        font-weight: bold;
        color: #039595;
      }
    }
  }

  .contents {
    flex: 1;
    overflow-y: auto;

    .classification {
      width: 200px;
      overflow-y: auto;
      box-sizing: border-box;

      &::-webkit-scrollbar {
        width: 8px; // y轴滚动条宽度
        height: 5px; // x轴滚动条宽度
        background-color: #fff;
        border-radius: 5px;
      }

      &::-webkit-scrollbar-thumb {
        background-image: -webkit-gradient(linear,
            left bottom,
            left top,
            color-stop(0.44, rgb(60 186 146)));
        border-radius: 5px;
        box-shadow: inset 0 0 6px #f4f4f5;
        transition: 0.3s ease-in-out;
      }
    }

    .results {
      width: calc(100% - 240px);
      margin: 0 20px;
      flex-direction: column;

      .searchResults {
        height: calc(100% - 55px);
        overflow-y: auto;

        &::-webkit-scrollbar {
          width: 8px; // y轴滚动条宽度
          height: 5px; // x轴滚动条宽度
          background-color: #fff;
          border-radius: 5px;
        }

        &::-webkit-scrollbar-thumb {
          background-image: -webkit-gradient(linear,
              left bottom,
              left top,
              color-stop(0.44, rgb(60 186 146)));
          border-radius: 5px;
          box-shadow: inset 0 0 6px #f4f4f5;
          transition: 0.3s ease-in-out;
        }

        .results_item {
          position: relative;
          margin: 10px 0;
          border-radius: 5px;
          box-shadow: 0 0 0 2px #f4f4f5;

          &:first-child {
            margin-top: 2;
          }

          img {
            margin: 0 15px;
            border-radius: 2px;
          }

          .index {
            font-weight: 500;
          }

          .results_content {
            flex-direction: column;
            justify-content: space-between;

            .title {
              font-size: 16px;
              // line-height: 25px;
              font-weight: 500;
            }

            .abstract {
              width: 99%;
              overflow: hidden;
              line-height: 20px;
              color: #999;
              text-overflow: ellipsis;
              white-space: nowrap;

              b {
                width: 50px;
                color: #000;
              }
            }

            b {
              font-size: 14px;
              font-weight: normal;
            }

            .author {
              display: flex;

              p {
                span {
                  text-decoration: underline;
                }
              }
            }

            .keywords {
              span {
                margin-right: 10px;
                // color: #4e6ef2;
                // text-decoration: underline;
              }
            }
          }
        }
      }
    }

    .paging {
      display: flex;
      width: 100%;
      height: 55px;
      background-color: #fff;
      border-radius: 5px;
      justify-content: center;
      align-items: center;
    }
  }
}

:deep(.el-checkbox--default) {
  height: 45px !important;
  line-height: 45px;
  color: #fff;
}

:deep(.el-checkbox__inner) {
  background-color: transparent;
}

:deep(.is-focus) {
  box-shadow: 0 0 0 0.5px var(--el-input-border-color, var(--el-border-color)) inset;
}

:deep(.el-pager) li {
  color: #4e6ef2;
}

:deep(.el-input__wrapper) li {
  box-shadow: 0 0 0 0.5px var(--el-input-border-color, var(--el-border-color)) inset !important;
}

:deep(.is-checked) .el-checkbox__inner {
  background-color: #039595;
}

:deep(.el-checkbox__inner)::after {
  border: 2px solid transparent;
  border-top: 0;
  border-left: 0;
}

:deep(.btn-next),
:deep(.btn-prev) {
  width: 70px;
  color: #4e6ef2;
  background-color: #f4f4f4 !important;
  border-radius: 5px;
}

:deep(.el-input-group__prepend) {
  padding: 0;
  border-radius: 25px 0 0 25px;
}

:deep(.el-row) {
  width: 100%;
  margin-bottom: 10px;
}

.popper {
  max-width: 500px !important;
}

.addbtn {
  width: 40px;
  margin-top: 2px;
  font-size: 20px;
  background-color: #207073;
}

.btn {
  width: 150px;
  height: 38px;
}

.searchBtn {
  display: flex;
  width: 100%;
  margin: auto;
  justify-content: center;
  align-items: center;

  .el-button {
    width: 70px;
    padding: 17px;
    box-sizing: border-box;

    &:first-child {
      background-color: #207073;
    }
  }
}

:deep(.el-tree-node__expand-icon) {
  display: none;
}

:deep(.is-focusable) {
  background-color: #039595;
}

:deep(.el-tree-node__children) {
  .is-expanded {
    max-height: 500px;
    overflow: auto;

    &::-webkit-scrollbar {
      width: 0; // y轴滚动条宽度
    }
  }

  .el-tree-node__content {
    .el-checkbox {
      // padding-left: 30px;
      display: inline-block;
      box-sizing: border-box;
    }
  }

  .el-tree-node {
    background-color: #207073;
  }
}

:deep(.el-tree-node__content) {
  height: 40px;

  .el-checkbox {
    display: none;
    margin-top: 5px;
    margin-right: 2px;
  }

  .treeContent {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  &:hover {
    background-color: #039595 !important;
  }
}

:deep(.el-tree-node.is-current > .el-tree-node__content) {
  background-color: transparent !important;
}

:deep(.el-input-group__append) {
  .searchbtn {
    padding: 0;
  }
}

:deep(.d-play-btn) {
  width: 45px;
  height: 45px;

  i {
    margin-left: 3px;
    font-size: 20px !important;
  }
}

:deep(.d-tool-item) {
  padding: 0 6px !important;
  box-sizing: border-box;

  i {
    font-size: 16px !important;
  }
}

:deep(.d-control-tool) {
  padding: 0 !important;
}

:deep(.d-player-state) {
  bottom: 50%;
  transform: translateY(40%);
}

.search-content {
  margin-left: 15px;
}

.book-right-button {
  position: absolute;
  top: 10px;
  right: 10px;
}
.classification {
  width: 200px;
  overflow-y: auto;
  box-sizing: border-box;

  &::-webkit-scrollbar {
    width: 8px; // y轴滚动条宽度
    height: 5px; // x轴滚动条宽度
    background-color: #fff;
    border-radius: 5px;
  }

  &::-webkit-scrollbar-thumb {
    background-image: -webkit-gradient(linear,
      left bottom,
      left top,
      color-stop(0.44, rgb(60 186 146)));
    border-radius: 5px;
    box-shadow: inset 0 0 6px #f4f4f5;
    transition: 0.3s ease-in-out;
  }
}
</style>
